#include <stdio.h> 
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdint.h>

#include "sm4.h"
#include "common_func.h"
#include "core_time.h"

//BSP板级支持包所需全局变量
unsigned long UART_BASE = 0xbf000000;					//UART16550的虚地址
unsigned long CONFREG_TIMER_BASE = 0xbf20f100;			//CONFREG计数器的虚地址
unsigned long CONFREG_CLOCKS_PER_SEC = 50000000L;		//CONFREG时钟频率
unsigned long CORE_CLOCKS_PER_SEC = 33000000L;			//处理器核时钟频率

uint8_t key[16] 	= {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 
					   0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10};
uint8_t plain[16] 	= {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 
					   0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10};	   
uint8_t chiper[16] 	= {0x68, 0x1e, 0xdf, 0x34, 0xd2, 0x06, 0x96, 0x5e, 
					   0x86, 0xb3, 0xe9, 0x4f, 0x53, 0x6e, 0x42, 0x46};		   
uint8_t result[16]  = {0};
uint8_t sm4_mode = 0;
uint8_t enc_done = 0;

int main(int argc, char** argv)
{
	printf("\nHello Loongarch32r SM4 INT!\n");

	uint32_t ret = 0;	   
	
	//enc------------------------------------------------
	sm4_mode = 0;
	ret = sm4_init(0, key);
	ret = sm4_enc_dec_int(plain);
	//enc------------------------------------------------
	
	while(1)
	{
		delay_ms(1);	//不添加仿真会失败
		if(enc_done == 1)
		{
			break;
		}
	}
	
	//dec------------------------------------------------
	sm4_mode = 1;
	ret = sm4_init(1, key);
	ret = sm4_enc_dec_int(chiper);
	//dec------------------------------------------------
	
	while(1){}
	
	return 0;
}

uint32_t sm4_call_back()
{
	if(sm4_mode == 0)
	{
		sm4_enc_dec_callback(result);
		if (memcmp(chiper, result, 16) == 0) 
		{
			printf("Enc success.\n");
		} else {
			printf("Enc Faild.\n");
		}
		enc_done = 1;
	}
	else
	{
		sm4_enc_dec_callback(result);
		if (memcmp(plain, result, 16) == 0) 
		{
			printf("Dec success.\n");
		} else {
			printf("Dec Faild.\n");
		}
		printf("SM4 INT test finished!\n");
	}

	RegWrite(0xbf20f00c, 0x20);//clr
}


void HWI0_IntrHandler(void)
{	
	unsigned int int_state;
	int_state = RegRead(0xbf20f014);

	if((int_state) == 0x20){
		sm4_call_back();
	}
}